package com.kui.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.kui.entity.Qikan;
import com.kui.entity.Type;
import com.kui.entity.User;
import com.kui.service.QikanService;
import com.kui.service.TypeService;

public class AddTypeServlet extends HttpServlet {

	
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		
		
		if("member".equals(user.getRole())){
			response.sendRedirect("main.jspx");
			return;
		}
		
		QikanService qs = new QikanService();
		List<Qikan> qikanlist = qs.findAll();
		request.setAttribute("qikanlist", qikanlist);
		/*response.setContentType("application/json");
		Gson gson = new Gson();
		String json = gson.toJson(qikanlist);
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();*/
		
		request.getRequestDispatcher("WEB-INF/views/addtype.jsp").forward(request, response);
		
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String bianhao = request.getParameter("bianhao");
		String name = request.getParameter("name");
		String qikan = request.getParameter("qikan");
		
		
		if(bianhao == null || name == null || "".equals(bianhao) || "".equals(name) || qikan == null || "empty".equals(qikan)){
			response.sendRedirect("addtype.jspx");
			return;
		}
		
		TypeService ts = new TypeService();
		Type t = ts.findById(bianhao,qikan);
		
		if(t != null){
			response.sendRedirect("addtype.jspx");
			return;
		}else {
			Type tt = new Type();
			tt.setId(bianhao);
			tt.setName(name);
			tt.setT_qikan_id(qikan);
			ts.save(tt);
			response.sendRedirect("type.jspx");
		}
	}

}
